<template>
  <div>
    <Card dis-hover>
      <!--搜索模块-->
      <Row>
        <Col span="20" class="margin-bottom-5">
          <!--高级搜索-->
          <div v-show="!searchList" style="display:inline-flex">
            <Input v-model="searchKey.contract_number" type="text" placeholder="合同编号" class="margin-right-5" size="small" style="width: 200px"></Input>
            <Select clearable v-model="searchKey.customer_id" class="margin-right-5" size="small" placeholder="客户名称" style="width: 200px">
              <Option v-for="item in customerList" :key="item.index" :value="item.customer_id">
                {{ item.customer_name }}
              </Option>
            </Select>
            <DatePicker v-model="searchKey.year" class="margin-right-5" size="small" type="year" placeholder="所属年份" style="width: 200px"></DatePicker>
            <DatePicker v-model="searchKey.month" class="margin-right-5 month" size="small" type="month" format="MM" placeholder="所属月份" style="width: 200px"></DatePicker>
            <Button class="margin-right-5" type="primary" size="small" icon="ios-search" @click="advencedSearch">
              搜索
            </Button>
            <Button type="primary" size="small" @click="closeSearch" icon="arrow-up-b">
              收起
            </Button>
          </div>
          <!--关键字搜索-->
          <div v-show="searchList">
            <Input v-model="searchKey.contract_number" type="text" placeholder="合同编号" class="margin-right-5" size="small" style="width: 200px"></Input>
            <Button class="margin-right-5" type="primary" size="small" icon="ios-search" @click="search">
              搜索
            </Button>
            <Button type="primary" size="small" icon="arrow-down-b" @click="openSearch">
              高级搜索
            </Button>
          </div>
        </Col>
        <Col span="4">
          <add-btn class="pull-right" @addClick="add"></add-btn>
        </Col>
      </Row>
      <Row>
        <Col span="1" style="text-align: center; margin-left: 1px">
          <Checkbox v-if="checkboxAccess"
                    v-model="checkAll"
                    @on-change="selectAllChange"
          ></Checkbox>
        </Col>
        <Col>
          <bulkreview-btn id="reviewBtn" @bulkreviewClick="bulkReview"></bulkreview-btn>
        </Col>
      </Row>
      <!--表格-->
      <div v-model="checkboxStatus" class="table-box" v-for="(item,index) in tableData" :key="index">
        <Row class="contract">
          <Col span="1" class="checkboxs">
            <Checkbox v-if="checkboxAccess"
                      v-model="(item.proportions[0].status == '已复核' || item.proportions[0].creator == userName) ? false : checkboxStatus[index]"
                      class="checkbox"
                      :disabled="item.proportions[0].status == '已复核' || item.proportions[0].creator == userName"
                      @on-change="selectChange(item.proportions, $event)"
            ></Checkbox>
          </Col>
          <Col span="5">
            <div class="contract-name bold">{{item.contract_name || '合同名称为空'}}</div>
            <div class="bottom"><span class="bold">对应客户：</span>{{item.customer_name}}</div>
          </Col>
          <Col span="5">
            <div class="bold" style="line-height: 48px">{{item.responsible}}/{{item.org_name}}</div>
            <div class="bottom"><span class="bold">合同编号：</span>{{item.contract_number}}</div>
          </Col>
          <Col span="5">
            <div></div>
            <div class="bottom"><span class="bold">合同金额：</span>{{item.contract_amount}}</div>
          </Col>
          <Col span="5">
            <div></div>
            <div><span class="bold">添加人：</span>{{item.proportions[0].creator}}</div>
          </Col>
          <Col span="2" offset="1">
            <div>
              <review-btn @reviewClick="review(item)"
                          :creator="item.proportions[0].creator"
                          :userName="userName"
                          :status="item.proportions[0].status"
              ></review-btn>
              <modify-btn @modifyClick="modify(item)"
                          :creator="item.proportions[0].creator"
                          :userName="userName"
                          :status="item.proportions[0].status"
              ></modify-btn>
              <delete-btn @delClick="remove(item)"
                          :creator="item.proportions[0].creator"
                          :userName="userName"
                          :status="item.proportions[0].status"
              ></delete-btn>
            </div>
          </Col>
        </Row>
        <Table :columns="column" :data="item.proportions" stripe></Table>
      </div>
      <Page :current="currentPage" :total="totalCount" :page-size="pageSize" show-total @on-change="changepage"></Page>
      <!--新建模块-->
      <Modal v-model="addModal"  title="新增可确认收入" width="800" ok-text="创建" @on-ok="submit" :loading="loading"  @on-cancel="cancel('addModal')">
        <Form :model="addForm" ref="addModal" label-position="right" :label-width="80" style="margin-top: 10px" :rules="ruleValidate">
          <Row>
            <Col span="10">
              <FormItem label="对应客户" prop="addFormCustomer">
                <Select clearable v-model="addFormCustomer" @on-change="customerChange">
                  <Option v-for="item in customerList" :key="item.index" :value="item.customer_id">
                    {{ item.customer_name }}
                  </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="10" offset="2">
              <FormItem label="合同编号" prop="contract_id">
                <Select clearable v-model="addForm.contract_id" @on-change="contractChange">
                  <Option v-for="item in contractList" :key="item.index" :value="item.contract_id">
                    {{ item.contract_number }}
                  </Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
              <FormItem label="合同金额">
                <Input v-model="contract.contract_amount" type="text" disabled></Input>
              </FormItem>
            </Col>
            <Col span="1">
              <span style="display: inline-block;width: 100%;line-height: 2.7;text-align: center">元</span>
            </Col>
            <Col span="10" offset="1">
              <FormItem label="签订日期">
                <Input v-model="contract.contract_date" type="text" disabled>111</Input>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
              <FormItem label="开始时间">
                <Input v-model="contract.contract_start_date" type="text" disabled></Input>
              </FormItem>
            </Col>
            <Col span="10" offset="2">
              <FormItem label="结束时间">
                <Input v-model="contract.contract_end_date" type="text" disabled></Input>
              </FormItem>
            </Col>
          </Row>
          <Row v-for="(item, index) in addForm.proportions" :key="index" type="flex" class="code-row-bg">
            <Col span="7">
              <FormItem label="年份" prop="year">
                <DatePicker v-model="item.year" type="year" placeholder="请选择" style="width: 100%"></DatePicker>
              </FormItem>
            </Col>
            <Col span="7" style="margin-left: -15px;margin-right: 15px">
              <FormItem label="月份" prop="month" class="month">
                <DatePicker v-model="item.month" type="month" format="MM" start-date="" placeholder="请选择" style="width: 100%"></DatePicker>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem label="摊销金额" prop="proportion_amount">
                <Input v-model="item.proportion_amount" type="text"></Input>
              </FormItem>
            </Col>
            <Col span="1">
              <span style="display: inline-block;width: 100%;line-height: 2.7;text-align: center">元</span>
            </Col>
            <Col span="1">
              <Button type="text" @click="removeProportion1(index)" :disabled="addForm.proportions.length == 1">
                <Icon type="android-cancel" size=17 style="margin: 4px 0 0 8px"></Icon>
              </Button>
            </Col>
          </Row>
          <Row type="flex" justify="center" class="code-row-bg">
            <Col span="4">
              <Button type="dashed" icon="plus" @click="addProportion1">继续添加可确认收入</Button>
            </Col>
          </Row>
        </Form>
      </Modal>
      <!--修改模块-->
      <Modal v-model="modifyModal" title="修改可确认收入" width="800" ok-text="修改" @on-ok="modifySubmit" :loading="loading">
        <Form :model="modifyForm" label-position="right" :label-width="80" style="margin-top: 10px">
          <Row>
            <Col span="10">
              <FormItem label="对应客户">
                <Input v-model="rowData.customer_name" type="text" disabled></Input>
              </FormItem>
            </Col>
            <Col span="10" offset="2">
              <FormItem label="合同编号">
                <Input v-model="rowData.contract_number" type="text" disabled></Input>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
              <FormItem label="合同金额">
                <Input v-model="rowData.contract_amount" type="text" disabled></Input>
              </FormItem>
            </Col>
            <Col span="1">
              <span style="display: inline-block;width: 100%;line-height: 2.7;text-align: center">元</span>
            </Col>
            <Col span="10" offset="1">
              <FormItem label="签订日期">
                <Input v-model="rowData.contract_date" type="text" disabled>111</Input>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
              <FormItem label="开始时间">
                <Input v-model="rowData.contract_start_date" type="text" disabled></Input>
              </FormItem>
            </Col>
            <Col span="10" offset="2">
              <FormItem label="结束时间">
                <Input v-model="rowData.contract_end_date" type="text" disabled></Input>
              </FormItem>
            </Col>
          </Row>
          <Row v-for="(item, index) in modifyForm.proportions" :key="index" type="flex" class="code-row-bg">
            <Col span="7">
              <FormItem label="年份">
                <DatePicker v-model="item.year" type="year" placeholder="请选择" style="width: 100%"></DatePicker>
              </FormItem>
            </Col>
            <Col span="7" style="margin-left: -15px;margin-right: 15px">
              <FormItem label="月份" class="month">
                <DatePicker v-model="item.month" type="month" format="MM" start-date="" placeholder="请选择" style="width: 100%"></DatePicker>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem label="摊销金额">
                <Input v-model="item.proportion_amount" type="text"></Input>
              </FormItem>
            </Col>
            <Col span="1">
              <span style="display: inline-block;width: 100%;line-height: 2.7;text-align: center">元</span>
            </Col>
            <Col span="1">
              <Button type="text" @click="removeProportion2(index)" :disabled="modifyForm.proportions.length == 1">
                <Icon type="android-cancel" size=17 style="margin: 4px 0 0 8px"></Icon>
              </Button>
            </Col>
          </Row>
          <Row type="flex" justify="center" class="code-row-bg">
            <Col span="4">
              <Button type="dashed" icon="plus" @click="addProportion2">继续添加可确认收入</Button>
            </Col>
          </Row>
        </Form>
      </Modal>
    </Card>
  </div>
</template>

<script>
  import addBtn from "./component/access-add-button.vue";
  import deleteBtn from "./component/access-delete-button.vue";
  import modifyBtn from "./component/access-modify-button.vue";
  import reviewBtn from "./component/access-review-button.vue";
  import bulkreviewBtn from "./component/access-bulkreview-button.vue";

  export default {
    data () {
      return {
        checkboxAccess: true,
        checkboxStatus: [],
        checkAll: false,
        userName: '',
        loading:true,
        searchList: true,
        searchKey: {
          customer_id: '',
          contract_number: '',
          contract_id: '',
          year: '',
          month: ''
        },
        customerList: [],
        contractList: [],
        contract: {},
        tableData:[],
        currentPage: 1,
        pageSize: 10,
        totalCount: 0,
        addModal: false,
        modifyModal: false,
        rowData: {},
        modifyForm: {},
        reviewList: [],
        addFormCustomer: '',
        addForm: {},
        column: [
          {
            title:'所属年份',
            key:'year',
            align: 'center',
          },
          {
            title:'所属月份',
            key:'month',
            align: 'center',
          },
          {
            title:'摊销金额',
            key:'proportion_amount',
            align: 'center',
          },
          {
            title:'状态',
            key:'status',
            align:'center',
            render:(h,params) => {
              if(params.row.status === '已复核') {
                return h('span',{},params.row.status)
              }else {
                return h('span',{
                  style:{
                    color:'#ed3f14'
                  }
                },params.row.status)
              }
            }
          },
          {
            title:'创建时间',
            key:'create_time',
            align: 'center',
            render:(h,params) => {
              return h('span',params.row.create_time.split(' ', 1)[0])
            }
          },
        ],
        ruleValidate:{
          contract_id: [
            { required: true, message: '请选择合同', trigger: 'change' }
          ]
        }
      };
    },
    methods: {
      init(searchKey) {
        this.customerChange("")
        this.reviewList = []
        this.checkAll = false
        var searchKey = searchKey || {
          customer_id: '',
          contract_number: '',
          contract_id: '',
          year: '',
          month: ''
        }
        let searchYear = ''
        let searchMonth = ''
        if (searchKey.year) searchYear = searchKey.year.getFullYear()
        if (searchKey.month) searchMonth = searchKey.month.getMonth() +1
        this.$http.get(`/fi/proportions/page?pageSize=${this.pageSize}&currentPage=${this.currentPage}&customer_id=${searchKey.customer_id}&contract_number=${searchKey.contract_number}&year=${searchYear}&month=${searchMonth}`).then((res) => {
          this.totalCount = res.data.returnValue.totalCount
          this.tableData = res.data.returnValue.data
        })
      },
      getCheckboxAccess(){
        let btn = document.getElementById('reviewBtn')
        let display = window.getComputedStyle(btn).display
        if(display == 'none') this.checkboxAccess = false
      },
      changepage(page){
        this.currentPage = page
        this.init()
      },
      closeSearch(){
        this.searchList = ! this.searchList
        this.searchKey = {
          customer_id: '',
          contract_id: '',
          year: '',
          month: ''
        }
      },
      openSearch(){
        this.getCustomer()
        this.searchList = ! this.searchList
        this.searchKey.contract_number = ''
      },
      addFormInit(){
        this.addFormCustomer = ''
        this.addForm = {
          contract_id: '',
          proportions: [
            {
              proportion_amount: '',
              year: '',
              month: '',
              status: '未复核',
            }
          ]
        }
      },
      getCustomer(){
        this.$http.get('/fi/customer/customers').then(res => {
          this.customerList = res.data.returnValue
        }).catch(() => {
          this.$Message.error("获取客户列表失败");
        })
      },
      customerChange(customer_id){
        this.$http.get(`/fi/contracts?customer_id=${customer_id}`).then(res => {
          this.contractList = res.data.returnValue.filter(contract => {
            return contract.proportions.length == 0
          })
        }).catch(() => {
          this.$Message.error('获取合同列表失败')
        })
      },
      contractChange(contract_id){
        this.contract = this.contractList.filter((contract) => {
          return contract.contract_id == contract_id
        })[0] || {}
      },
      advencedSearch(){
        this.init(this.searchKey)
      },
      search(){
        this.init(this.searchKey)
      },
      add(){
        this.getCustomer()
        this.addFormInit()
        this.addModal = true
      },
      addProportion1(){
        this.addForm.proportions.push({
          proportion_amount: '',
          year: '',
          month: '',
          status: '未复核'
        })
      },
      addProportion2(){
        this.modifyForm.proportions.push({
          proportion_amount: '',
          year: '',
          month: '',
          status: '未复核'
        })
      },
      removeProportion1(index){
        this.addForm.proportions.splice(index, 1)
      },
      removeProportion2(index){
        this.modifyForm.proportions.splice(index, 1)
      },
      submit(){
        this.$refs['addModal'].validate((valid) => {
          if(valid){
            let flag = this.vaildateEmpty(this.addForm)
            if (flag) {
              this.addForm.proportions.map((proportion) => {
                proportion.year = proportion.year.getFullYear()
                proportion.month = proportion.month.getMonth() + 1
                return proportion
              })
              this.$http.put('/fi/proportions', this.addForm).then( res => {
                this.addFormInit()
                this.currentPage = 1
                this.init()
                this.$Message.success(res.data.message);
                this.$refs['addModal'].resetFields()
                this.addModal = false
              }).catch(() => {
                let proportions = this.addForm.proportions
                this.addForm.proportions = []
                this.pushProportions(this.addForm, proportions)
                this.wraning()
                let sum = 0
                for (let proportion of this.addForm.proportions) sum += proportion.proportion_amount
                if (sum != this.contract.contract_amount) {
                  this.$Message.error('可确认收入总金额与合同金额不符！')
                } else {
                  this.$Message.error('新建可确认收入失败')
                }
              })
            } else {
              this.wraning('请将可确认收入的年份、月份和摊销金额都填写完整！')
            }
          }else {
            this.wraning()
          }
        })
      },
      vaildateEmpty(form){
        for (let proportion of form.proportions) {
          if (! (proportion.year && proportion.month && proportion.proportion_amount)) {
            return false
          }
        }
        return true
      },
      wraning(string){
        this.loading = false
        this.$nextTick(() => {
          this.loading = true
        })
        if (string) {
          this.$Message.error(string)
        }
      },
      pushProportions(form, proportions){
        for (let proportion of proportions) {
          form.proportions.push({
            proportion_id: proportion.proportion_id,
            proportion_amount: proportion.proportion_amount,
            year: this.string2date(proportion.year + 1, 'year'),
            month: this.string2date(proportion.month, 'month'),
            status: '未复核'
          })
        }
      },
      string2date(string, type){
        if (type == 'year') {
          let date = new Date(string, 0, 0, 0, 0, 0, 0)
          return date
        } else {
          let date = new Date(0, string, 0, 0, 0, 0, 0)
          return date
        }
      },
      detail(item){
        this.$router.push({
          name:'fi_receivable-mgt-detail',
          query:item
        })
      },
      modifyFormInit(rowData){
        this.modifyForm = {
          contract_id: rowData.contract_id,
          proportions: []
        }
        let proportions = rowData.proportions
        this.pushProportions(this.modifyForm, proportions)
      },
      modify(rowData){
        this.rowData = rowData;
        this.modifyFormInit(rowData)
        this.modifyModal = true;
      },
      modifySubmit(){
        let flag = this.vaildateEmpty(this.modifyForm)
        if (flag) {
          this.modifyForm.proportions.map((proportion) => {
            proportion.year = proportion.year.getFullYear()
            proportion.month = proportion.month.getMonth() + 1
            return proportion
          })
          this.$http.put('/fi/proportions', this.modifyForm).then( res => {
            this.init(this.searchKey)
            this.modifyModal = false
            this.$Message.success('修改成功！');
            this.currentPage = 1
            this.init()
          }).catch(() => {
            this.wraning()
            let sum = 0
            for (let proportion of this.modifyForm.proportions) sum += proportion.proportion_amount
            if (sum != this.rowData.contract_amount) {
              this.$Message.error('可确认收入总金额与合同金额不符！')
            } else {
              this.$Message.error('修改可确认收入失败！')
            }
            this.modifyFormInit(this.rowData)
          })
        } else {
          this.wraning('请将可确认收入的年份、月份和摊销金额都填写完整！')
        }
      },
      review(data){
        let arr
        if(data[0]) {
          arr = data
        } else {
          arr = []
          arr.push(data)
        }
        let body = {
          proportion_ids: [],
          status: '已复核'
        }
        for (let contract of arr) {
          for (let proportion of contract.proportions || contract){
            body.proportion_ids.push(proportion.proportion_id)
          }
        }
        if(! body.proportion_ids[0]){
          this.$Message.warning('您未选中任何可确认收入！')
        } else {
          this.$http.put('/fi/proportions/status', body).then(() => {
            this.init()
            this.$Message.success('更改复核状态成功！')
          })
        }
      },
      selectAllChange(value){
        if(value){
          this.checkboxStatus = []
          for (let i = 0; i < this.pageSize; ++i) {
            this.checkboxStatus.push(true)
          }
          this.reviewList = []
          for (let contract of this.tableData) {
            if(contract.proportions[0].status == '未复核' && contract.proportions[0].creator != this.userName) {
              this.reviewList.push(contract.proportions)
            }
          }
        }else {
          this.checkboxStatus = []
          for (let i = 0; i < 10; ++i) {
            this.checkboxStatus.push(false)
          }
          this.reviewList = []
        }
      },
      selectChange(proportions, value){
        if (this.checkboxStatus.length == this.pageSize){
          let flag = true
          for(let status of this.checkboxStatus) {
            flag = flag && status
          }
          if (flag) this.checkAll = true
        }
        if(value) {
          this.reviewList.push(proportions)
        } else {
          this.checkAll = false
          for(let i = 0; i < this.reviewList.length; ++i){
            if(this.reviewList[i] == proportions) {
              this.reviewList.splice(i, 1)
              i -= 1
            }
          }
        }
      },
      bulkReview(){
        this.review(this.reviewList)
      },
      remove(item){
        this.$Modal.confirm({
          title: '确认',
          content: `您确定要删除合同编号为: ${item.contract_number} 的合同中包含的全部可确认收入吗？`,
          onOk: () => {
            this.$http.delete(`/fi/contracts/${item.contract_id}/proportions`).then(res => {
              if(this.tableData.length == 1 && this.currentPage > 1) {
                this.currentPage -= 1
              }
              this.init()
              this.$Message.success('删除成功！')
            }).catch(() => {
              this.$Message.error('删除失败！')
            })
          }
        })
      },
      cancel(name) {
        this.$refs[name].resetFields()
      },
    },
    components: {
      addBtn,
      deleteBtn,
      modifyBtn,
      reviewBtn,
      bulkreviewBtn,
    },
    computed: {},
    watch: {},
    mounted () {
      this.userName = this.$auth.user().name
      this.getCheckboxAccess()
      this.init()
    },
  };

</script>
<style>
  @import "../../../../styles/common.less";

  .month .ivu-date-picker-header {
    display: none;
  }
  .table-box {
    margin-bottom: 10px;
  }
  .contract {
    height: 80px;
    background: rgb(248, 248, 249);;
    border: 1px solid #dddee1;
    border-bottom: none;
    font-size: 12px;
  }
  .contract div {
    height: 40px;
    line-height: 40px;
  }
  .contract-name {
    font-size: 18px;
  }
  .checkboxs {
    height: 80px;
    text-align: center;
  }
  .bold {
    font-weight: bold;
  }
</style>